import bcrypt from 'bcryptjs'
import { nanoid } from 'nanoid'

// seed users (password: 123456)
const passwordHash = bcrypt.hashSync('123456', 8)
export const users = [
  { id: 1, username: 'stu1', name: '张三', role: 'student', passwordHash },
  { id: 2, username: 'tea1', name: '李老师', role: 'teacher', passwordHash },
  { id: 3, username: 'admin', name: '管理员', role: 'admin', passwordHash },
]

// seed leaves
let idSeq = 1000
export const leaves = Array.from({ length: 20 }).map((_, idx) => {
  const day = String((idx % 28) + 1).padStart(2, '0')
  const startAt = `2025-11-${day}T09:00:00.000Z`
  const endAt = `2025-11-${day}T18:00:00.000Z`
  const status = idx % 5 === 0 ? 'rejected' : idx % 2 === 0 ? 'pending' : 'approved'
  return {
    id: idSeq++,
    studentId: 1,
    type: idx % 3 === 1 ? 'sick' : 'personal',
    startAt,
    endAt,
    hours: 9,
    reason: '示例数据',
    attachmentUrl: null,
    status,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    steps: [
      {
        id: nanoid(),
        title: '提交申请',
        comment: '申请已提交',
        status: 'approved',
        actedBy: 1,
        actedAt: new Date().toISOString(),
        stepOrder: 1,
      },
      {
        id: nanoid(),
        title: '老师审批',
        comment: status === 'pending' ? '待处理' : status === 'approved' ? '同意' : '不同意',
        status: status === 'approved' ? 'approved' : status === 'rejected' ? 'rejected' : 'pending',
        actedBy: status === 'pending' ? null : 2,
        actedAt: status === 'pending' ? null : new Date().toISOString(),
        stepOrder: 2,
      },
    ],
  }
})

export function createLeave({ studentId, type, startAt, endAt, reason }) {
  const id = idSeq++
  const hours = Math.max(0, Math.round((new Date(endAt) - new Date(startAt)) / 36e5))
  const now = new Date().toISOString()
  const item = {
    id,
    studentId,
    type,
    startAt,
    endAt,
    hours,
    reason,
    attachmentUrl: null,
    status: 'pending',
    createdAt: now,
    updatedAt: now,
    steps: [
      {
        id: nanoid(),
        title: '提交申请',
        comment: '申请已提交',
        status: 'approved',
        actedBy: studentId,
        actedAt: now,
        stepOrder: 1,
      },
      {
        id: nanoid(),
        title: '老师审批',
        comment: '待处理',
        status: 'pending',
        actedBy: null,
        actedAt: null,
        stepOrder: 2,
      },
    ],
  }
  leaves.unshift(item)
  return item
}
